import tkinter as tk
from tkinter import messagebox
import requests

class LoginWindow:
    def __init__(self, parent, main_app, login_type):
        self.main_app = main_app
        self.login_type = login_type  # 'user' or 'admin'
        
        self.window = tk.Toplevel(parent)
        self.window.title("用户登录" if login_type == "user" else "管理员登录")
        self.window.geometry("400x300")
        self.window.configure(bg='#f0f0f0')
        self.window.transient(parent)
        self.window.grab_set()
        
        self.create_widgets()
    
    def create_widgets(self):
        # 标题
        title_text = "用户登录" if self.login_type == "user" else "管理员登录"
        title_label = tk.Label(
            self.window,
            text=title_text,
            font=("Arial", 18, "bold"),
            bg='#f0f0f0',
            fg='#2c3e50'
        )
        title_label.pack(pady=20)
        
        # 表单框架
        form_frame = tk.Frame(self.window, bg='#f0f0f0')
        form_frame.pack(pady=20)
        
        # 用户名
        tk.Label(form_frame, text="用户名:", bg='#f0f0f0', font=("Arial", 12)).grid(row=0, column=0, sticky='e', pady=10, padx=5)
        self.username_entry = tk.Entry(form_frame, font=("Arial", 12), width=20)
        self.username_entry.grid(row=0, column=1, pady=10, padx=5)
        
        # 密码
        tk.Label(form_frame, text="密码:", bg='#f0f0f0', font=("Arial", 12)).grid(row=1, column=0, sticky='e', pady=10, padx=5)
        self.password_entry = tk.Entry(form_frame, font=("Arial", 12), width=20, show='*')
        self.password_entry.grid(row=1, column=1, pady=10, padx=5)
        
        # 按钮框架
        button_frame = tk.Frame(self.window, bg='#f0f0f0')
        button_frame.pack(pady=20)
        
        # 登录按钮
        login_btn = tk.Button(
            button_frame,
            text="登录",
            command=self.login,
            font=("Arial", 12),
            bg='#3498db',
            fg='white',
            width=10
        )
        login_btn.grid(row=0, column=0, padx=10)
        
        # 取消按钮
        cancel_btn = tk.Button(
            button_frame,
            text="取消",
            command=self.window.destroy,
            font=("Arial", 12),
            bg='#95a5a6',
            fg='white',
            width=10
        )
        cancel_btn.grid(row=0, column=1, padx=10)
        
        # 绑定回车键
        self.window.bind('<Return>', lambda event: self.login())
    
    def login(self):
        username = self.username_entry.get().strip()
        password = self.password_entry.get().strip()
        
        if not username or not password:
            messagebox.showerror("错误", "请输入用户名和密码")
            return
        
        try:
            if self.login_type == "user":
                response = requests.post(
                    f"{self.main_app.api_base}/login",
                    json={"username": username, "password": password}
                )
                result = response.json()
                
                if result['success']:
                    messagebox.showinfo("成功", "登录成功！")
                    self.window.destroy()
                    self.main_app.user_login_success(result['user'])
                else:
                    messagebox.showerror("错误", result['message'])
            
            else:  # admin
                response = requests.post(
                    f"{self.main_app.api_base}/admin/login",
                    json={"username": username, "password": password}
                )
                result = response.json()
                
                if result['success']:
                    messagebox.showinfo("成功", "管理员登录成功！")
                    self.window.destroy()
                    self.main_app.admin_login_success(result['admin'])
                else:
                    messagebox.showerror("错误", result['message'])
                    
        except requests.exceptions.ConnectionError:
            messagebox.showerror("错误", "无法连接到服务器，请检查后端服务是否启动")
        except Exception as e:
            messagebox.showerror("错误", f"登录失败: {str(e)}")